<template>
  <VPage>
    <div class="flex">
      <div class="leftWrap" v-if="props.type != 'problem_order'">
        <div class="transition-all duration-[300]">
          <el-tree
            v-if="pageComfig.isShowLeft"
            class="leftTree"
            :data="treeData"
            :props="defaultProps"
            @node-click="handleNodeClick"
            :check-on-click-node="true"
            :expand-on-click-node="false"
            :highlight-current="true"
            :default-expand-all="true"
          />
        </div>
        <span class="isShowLeft" @click="showLeftF">
          <svg-icon icon-class="arrow_down" :class="`w-[100%] h-[100%]  ${pageComfig.isShowLeft ? 'rotate-[90deg]' : 'rotate-[270deg]'}`" />
        </span>
      </div>

      <VTable
        v-if="tableRefShow"
        ref="tableRef"
        v-bind="tableOptins"
        class="oms-order-rightWrap table-view"
        :class="{ 'order-table-body': activeName == 1 || activeName == 2 }"
        @checkbox-change="checkboxChange"
        @checkbox-all="checkboxChange"
        @form-reset="formReset"
      >
        <template #high_form="{ form }">
          <XForm ref="form" :fieldList="highFieldList" :options="formOption" labelPosition="top" :formData="form" :originOption="originOption">
            <template #ExecuteOrderStrategy>
              <!-- 订单排程策略 -->
              <el-select v-model="form.is_execute_order_strategy" placeholder="是否执行" clearable class="mr-[8px] w-108">
                <el-option v-for="item in strategyOpt" :key="item.value" :label="item.label + '订单排程策略'" :value="item.value" />
              </el-select>
              <el-select v-model="form.strategy_schedule_id" placeholder="订单排程策略" filterable clearable class="w-[208px]">
                <el-option v-for="item in strategyExecuteOpt" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </template>

            <template #ExecutSplittingStrategy>
              <!-- 分仓策略 -->
              <el-select v-model="form.is_execute_splitting_strategy" placeholder="是否执行" clearable class="mr-[8px] w-108">
                <el-option v-for="item in strategyOpt" :key="item.value" :label="item.label + '物流分仓策略'" :value="item.value" />
              </el-select>
              <el-select v-model="form.splitting_strategy_id" placeholder="物流分仓策略" filterable clearable class="w-[208px]">
                <el-option v-for="item in preferredOpt" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </template>
            <!-- 分类 -->
            <template #SpuCategory>
              <SelectProductCategories filterable multiple collapse-tags slotType="cascader" style="width: 370px" v-model:modelValue="form['products.categories']" placeholder="产品分类" />
            </template>

            <!-- 平台运输方式 -->
            <template #ShippingMethod>
              <el-select v-model="form.platform_shipping_method_id" placeholder="平台运输方式" class="w-[100%]" multiple clearable filterable collapse-tags>
                <el-option-group v-for="group in originOption.shippingService" :key="group.label" :label="group.label">
                  <el-option v-for="item in group.options" :key="item.value" :label="item.label" :value="item.value" />
                </el-option-group>
              </el-select>
            </template>
          </XForm>
        </template>

        <template #form="{ form }">
          <el-tabs v-model="activeName" class="list-tabs w-[100%] mt-[-8px]" @tab-change="handleClick" v-if="props.type != 'problem_order'">
            <el-tab-pane label="全部订单" :name="0"></el-tab-pane>
            <el-tab-pane label="可合并订单" :name="1"></el-tab-pane>
            <el-tab-pane label="已合并订单" :name="2"></el-tab-pane>
          </el-tabs>
          <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption" v-if="show">
            <template #ShopCascade>
              <SelectsShopCascade v-model:platform="form.platform_id" multiple v-model:site="form.site_id" v-model:shop="form.shop_id" />
            </template>
            <template #ShipWarehouse>
              <SelectWarehouse placeholder="发货仓库" multiple collapseTags v-model:modelValue="form.ship_warehouse_id" style="width: 240px" />
            </template>
            <template #ShippingMethod>
              <SelectShippingMethod placeholder="运输方式" multiple collapseTags v-model:modelValue="form.shipping_method_id" style="minwidth: 200px" />
            </template>
            <template #RecipientCountry>
              <SelectCountry placeholder="收货国家" multiple collapseTags labelKey2="true" v-model:modelValue="form.recipient_country_id" style="width: 240px" ref="SelectCountryRef" />
            </template>
          </XForm>
        </template>

        <template #toolbar_btns>
          <ActionBars
            :type="type"
            :active="activeName"
            @setParamGet="setParamGet"
            :totalInfo="orderTotal"
            :rows="multipleSelection"
            @refresh="getList"
            @expand="handleExpand"
            :params="queryListParams"
            v-model:showOrderProfit="showOrderProfit"
            @shopSaleList="openShopSaleList"
          />
        </template>

        <template #Goods="{ row }">
          <div :id="`${row.id}-order-can-merged`">
            <div v-if="row?.problem_cause_id_desc?.length" class="problem-row" @click="handleProblem(row)">
              <div class="sticky" style="z-index: 9">
                <VText title="异常信息" :value="`${row.problem_cause_id_desc.join('，')}${row.problem_causes ? ' ' + row.problem_causes : ''}`" :line="1" class="w-[100%]" />
              </div>
            </div>
            <ExpandList class="product-list" :show-expand="row?.items?.length > 1" v-model:expand="row.expandStatus" @change="rendererView" :length="row?.items?.length">
              <template #default="{ expand }">
                <div class="product-item" v-for="(item, index) in getRows(row, expand)" :key="`${item.sku}${index}`">
                  <div class="tag-count">
                    <div>{{ row.original_order_currency }} {{ item.original_amount }}</div>
                  </div>
                  <div class="product-info">
                    <el-image class="w-[74px] h-[74px] mr-[4px]" style="border: 0.5px solid #f0f0f0; border-radius: 4px" :src="item.main_img || ''" fit="fill">
                      <template #error>
                        <img src="~@/assets/images/null-img.png" alt="" />
                      </template>
                    </el-image>

                    <div class="info">
                      <div class="flex items-center">
                        <span>
                          <VText title="系统SKU" :value="item.sku || '点击添加SKU'" type="link" :copy="true" @click="onSku(row, item)" />
                        </span>
                        <span class="text-[red] ml-[4px]"> *{{ item.quantity }} </span>

                        <!-- 采购历史记录 -->
                        <el-tooltip content="采购历史记录" placement="top" v-if="item.sku">
                          <img src="~@/assets/images/lishijilu.png" class="w-[18px] h-[18px] ml-[8px] cursor-pointer" alt="" @click="purchaseDtlOpen(row, item)" />
                        </el-tooltip>

                        <!-- 二手维修编号 -->
                        <el-tag type="danger" effect="dark" size="small" class="repair_tag" v-if="item.repair_number.length" @click="openTableInfo('repairNumber', item)">维修</el-tag>

                        <!-- 产品等级 -->
                        <el-tooltip content="产品等级" placement="top" v-if="item.product_level_desc">
                          <div class="logistics-attr">{{ item.product_level_desc }}</div>
                        </el-tooltip>
                      </div>

                      <VText title="自定义SKU" :value="item.custom_sku" :line="1" :copy="true" />
                      <VText title="渠道SKU" :value="item.platform_sku" :line="1" :copy="true" class="w-[200px]" />
                    </div>
                  </div>
                  <VText :value="item.sku_cn_title || ''" :line="1" />

                  <div class="product-item-footer">
                    <div class="flex">
                      <p class="w-[162px]">
                        <VText title="ASIN" :value="item.asin" :line="1" :copy="true" type="link" @click="openAsinLink(item)" />
                      </p>

                      <!-- <VText title="库存" :value="item.available_stock" :line="1" type="link" @click="openTableInfo('inventory', item)" /> -->
                      <!-- @mouseenter="mouseenter($event, item)" @mouseleave="mouseleave" -->
                      <span class="v-tip-content v-tip-content-wrap">
                        <VText title="库存" :value="item.available_stock" :line="1" type="link" @click="openInventorySee(item, row)" />
                      </span>

                      <!-- <el-button @mouseenter="mouseenter($event, item)" @mouseleave="mouseleave" class="v-tip-content v-tip-content-wrap">Top center</el-button> -->
                    </div>

                    <div>
                      <el-tooltip v-if="item.shipping_logistics_attr" content="物流属性" placement="top">
                        <div class="logistics-attr">
                          {{ item.shipping_logistics_attr }}
                        </div>
                      </el-tooltip>

                      <el-tooltip content="SKU销售状态" placement="top">
                        <div class="logistics-attr">
                          {{ item.sales_status_desc || "正常" }}
                        </div>
                      </el-tooltip>

                      <el-tooltip content="组合SKU" placement="top" v-if="item.is_assemble">
                        <div class="logistics-attr" @click="openAssembles(item, row)">组合</div>
                      </el-tooltip>
                    </div>
                  </div>
                </div>
              </template>
            </ExpandList>
          </div>
        </template>

        <!-- 订单金额 -->
        <template #OrderPrice="{ row }">
          <div>
            <div class="flex items-center">
              <country-flag :country="getFlag(row?.recipient?.recipient_country?.toLowerCase())" class="mr-[6px] mb-2" size="big" shadow />
              <div>{{ row.recipient.country_cn }}</div>
            </div>

            <VText title="支付金额" :value="`${row.original_order_currency} ${row.original_order_amount || '0'}`" :line="1" />
            <VText title="产品总价" :value="`${row.original_order_currency} ${row.order_amount || '0'}`" :line="1" />
            <!-- 退款状态 -->
            <span class="text-red" v-if="row?.refund_status != 0">
              <VText title="{row.refund_status_desc}" value="{`${row.original_order_currency}" -${row?.payment?.refund_amount_tax}`} line="{1}" />
            </span>

            <VText title="运费收入" v-if="row?.shipping_revenue" :value="`${row.original_order_currency} ${row.shipping_revenue}`" :line="1" />

            <VText title="优惠金额" v-if="row?.discount_amount" :value="`${row.original_order_currency} ${row.discount_amount}`" :line="1" />

            <VText title="其他收入" v-if="row?.other_price" :value="`${row.original_order_currency} ${row.other_price}`" :line="1" />

            <VText title="税费收入" v-if="row?.tax_amount" :value="`${row.original_order_currency} ${row.tax_amount}`" :line="1" />
            <div v-if="showOrderProfit">
              <div class="flex items-center">
                <div><VText title="利润" :value="row.total_order_profit ? `CNY ${row.total_order_profit}` : '0'" :line="1" :class="row.total_order_profit < 0 ? 'text-red' : ''" /></div>
                <div class="flex-1 ml-[4px]">
                  <div
                    :class="`w-[24px] h-[14px] text-[10px] text-[#fff] border-radius-[2px] px-[1px] align-center ${row.settlement_status == 1 ? 'bg-[#3487FF]' : 'bg-[#FF6334]'}`"
                    style="line-height: 14px"
                  >
                    {{ row.settlement_status == 1 ? "真实" : "预估" }}
                  </div>
                </div>
              </div>
              <VText
                title="利润率"
                :value="row.total_order_profit_rate ? `${(row.total_order_profit_rate * 100).toFixed(2)}%` : '0'"
                :line="1"
                :class="row.total_order_profit_rate < 0 ? 'text-red' : ''"
              />
            </div>
          </div>
        </template>

        <template #OrderCanMergedTem="{ row }">
          <div :id="`${row.id}-order-can-merged`">
            <div class="order-row line qqqqq" v-for="item in row.child" :key="item.id">
              <ExpandList :show-expand="item.items?.length > 1" v-model:expand="item.expandStatus" @change="rendererView" :length="item.items?.length" class="product-list">
                <template #default="{ expand }">
                  <div v-for="(goodsVal, index) in getRows(item, expand)" :key="index">
                    <div class="order-item">
                      <div class="items-left order-goods">
                        <div class="tag-count">
                          <span class="mr-[6px]"> {{ item.original_order_currency }} {{ goodsVal.original_amount }}</span>
                        </div>

                        <div class="flex">
                          <el-image class="w-[74px] h-[74px] mr-[4px]" style="border: 0.5px solid #f0f0f0; border-radius: 4px" :src="goodsVal?.main_img" fit="fill">
                            <template #error>
                              <img src="~@/assets/images/null-img.png" alt="" />
                            </template>
                          </el-image>
                          <div class="flex-1 p-[0] m-[0]">
                            <div class="value mb-[4px]">
                              {{ goodsVal?.sku || "-" }}
                              <span class="text-[red]"> *{{ goodsVal.quantity }} </span>
                            </div>
                            <VText title="自定义SKU" :value="goodsVal.custom_sku" :line="1" />
                            <VText title="渠道SKU" :value="goodsVal.platform_sku" :line="1" />
                          </div>
                        </div>

                        <VText :value="goodsVal.sku_cn_title || ''" :line="1" />
                        <div class="product-item-footer">
                          <p class="no-txt w-[148px] label">
                            ASIN: <span class="value">{{ goodsVal.asin || "-" }}</span>
                          </p>
                          <p class="no-txt cursor-pointer min-w-[40px] max-w-[80px] label">
                            库存: <span class="value">{{ goodsVal.available_stock || "-" }}</span>
                          </p>

                          <div class="flex-1" style="text-align: right">
                            <el-tooltip v-if="goodsVal.shipping_logistics_attr" content="物流属性" placement="top">
                              <el-button plain size="small" style="margin-left: 4px">
                                {{ goodsVal.shipping_logistics_attr }}
                              </el-button>
                            </el-tooltip>
                            <el-tooltip content="SKU销售状态" placement="top">
                              <el-button plain size="small" style="margin-left: 4px">{{ goodsVal.sales_status_desc || "正常" }}</el-button>
                            </el-tooltip>
                            <el-tooltip content="组合SKU" placement="top" v-if="goodsVal.is_assemble">
                              <el-button plain size="small" style="margin-left: 4px">组合</el-button>
                            </el-tooltip>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
              </ExpandList>
            </div>
          </div>
        </template>

        <template #OrderMergedTem="{ row }">
          <div :id="`${row.id}-order-can-merged`">
            <div class="order-row line" v-for="item in row.child" :key="item.id">
              <ExpandList :show-expand="item.items?.length > 1" v-model:expand="item.expandStatus" @change="rendererView" :length="item.items?.length">
                <template #default="{ expand }">
                  <div v-for="(goodsVal, index) in getRows(item, expand)" :key="index">
                    <div class="order-item">
                      <div class="items-left order-goods">
                        <div class="tag-count">
                          <span class="mr-[6px]"> {{ item.original_order_currency }} {{ goodsVal.original_amount }}</span>
                        </div>

                        <div class="flex">
                          <el-image class="w-[74px] h-[74px] mr-[4px]" style="border: 0.5px solid #f0f0f0; border-radius: 4px" :src="goodsVal?.main_img" fit="fill">
                            <template #error>
                              <img src="~@/assets/images/null-img.png" alt="" />
                            </template>
                          </el-image>
                          <div class="flex-1 p-[0] m-[0]">
                            <div class="mb-[4px]">
                              {{ goodsVal?.sku || "-" }}
                              <span class="text-[red]"> *{{ goodsVal.quantity }} </span>
                            </div>
                            <div>
                              <label>自定义SKU：</label>
                              <span class="value">{{ goodsVal?.custom_sku || "-" }}</span>
                            </div>
                            <div>
                              <label>渠道SKU：</label>
                              <span class="value">{{ goodsVal?.platform_sku || "-" }}</span>
                            </div>
                          </div>
                        </div>

                        <VText :value="goodsVal.sku_cn_title || ''" :line="1" />
                        <div class="product-item-footer">
                          <p class="no-txt w-[148px] label">
                            ASIN: <span class="value">{{ goodsVal.asin || "-" }}</span>
                          </p>
                          <p class="no-txt cursor-pointer min-w-[40px] max-w-[80px] label">
                            库存: <span class="value">{{ goodsVal.available_stock || "-" }}</span>
                          </p>

                          <div class="flex-1" style="text-align: right">
                            <el-tooltip v-if="goodsVal.shipping_logistics_attr" content="物流属性" placement="top">
                              <el-button plain size="small" style="margin-left: 4px">
                                {{ goodsVal.shipping_logistics_attr }}
                              </el-button>
                            </el-tooltip>
                            <el-tooltip content="SKU销售状态" placement="top">
                              <el-button plain size="small" style="margin-left: 4px">{{ goodsVal.sales_status_desc || "正常" }}</el-button>
                            </el-tooltip>
                            <el-tooltip content="组合SKU" placement="top" v-if="goodsVal.is_assemble">
                              <el-button plain size="small" style="margin-left: 4px">组合</el-button>
                            </el-tooltip>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
              </ExpandList>
            </div>
          </div>
        </template>
      </VTable>
    </div>
  </VPage>

  <el-popover ref="tipRef" :virtual-ref="tip.ref" trigger="click" placement="right" :visible="tip.visible" virtual-triggering width="280px">
    <div>
      <VText title="组合SKU" :value="tip?.data.skuData?.sku" :line="1" v-if="tip?.data?.assemblesData?.length" />
      <el-table :data="tip?.data?.skuData?.inventory" border style="width: 100%">
        <el-table-column prop="warehouse_name" label="仓库名称" />
        <el-table-column prop="num" label="可用库存" width="100" />
      </el-table>
      <div v-if="tip?.data?.assemblesData?.length">
        <div v-for="item in tip?.data?.assemblesData" :key="item.sku">
          <VText title="子SKU" :value="`${item?.sku}*${item.quantity}`" :line="1" />
          <el-table :data="item?.inventory" border style="width: 100%">
            <el-table-column prop="warehouse_name" label="仓库名称" />
            <el-table-column prop="num" label="可用库存" width="100" />
          </el-table>
        </div>
      </div>
    </div>
  </el-popover>

  <!-- 日志/ -->
  <Log dialog v-model="logVisible" :autoLoad="false" tag="order" :business_id="logId" />

  <!-- 无法关联SKU -->
  <!-- <UnableAssociateSku v-model="unableSkuVisible" ref="UnableAssociateSkuRef" :rows="selectRow" @refresh="getList" /> -->
  <UnableAssociateSku v-model="unableSkuVisible" ref="UnableAssociateSkuRef" @refresh="getList" />
  <!-- 备注编辑 -->
  <EditRemarks ref="editRemarksRef" @refresh="getList" />

  <!-- 查看组合sku信息 -->
  <AssembleSkuSee ref="assembleSkuSee" @openStock="openTableInfo" />

  <!-- sku 库存信息查看 -->
  <InventorySee ref="InventorySeeRef" />

  <!--  收件地址 弹窗 -->
  <RecipientAddress ref="RecipientAddressRef" />

  <!-- 弹窗 表单编辑 -->
  <OrderConfirmInput v-model="orderConfirmInputVisible" v-bind="orderCurrentConfirm" @submit="handleConfirmInputSubmit" />

  <!-- 弹窗 表格数据展示 -->
  <DialogTableInfo v-model="dialogTableInfoVisible" v-bind="tableInfoConfirm" />

  <!-- 采购历史记录 -->
  <PurchaseDtl ref="PurchaseDtlRef" />
</template>

<script setup lang="jsx" name="userList">
const router = useRouter()
//  弹窗 表单编辑
import { confirm } from "./AllOrder/ActionBars/config.js"
import OrderConfirmInput from "./Batch/OrderConfirmInput/index.vue"
const orderConfirmInputVisible = ref(false)
const orderCurrentConfirm = ref({})
// 弹窗 表单编辑 保存
const handleConfirmInputSubmit = async (e) => {
  try {
    const { input } = e
    let params = {}
    let msg = ""
    let requests = () => {}
    switch (orderCurrentConfirm.value.type) {
      case "recipientAddress": // 编辑 收件地址
        requests = orderCurrentConfirm?.value?.api
        params = {
          id: input.id,
          order: { id: input.id },
          recipient: {
            ...input,
            recipient_country_id: originOption.value.countryOpt.find((v) => v.country == input.recipient_country)?.id,
          },
        }
        msg = "保存成功"
        break
    }
    requests(params).then((res) => {
      ElMessage.success(msg)
      orderConfirmInputVisible.value = false
      getList()
    })
  } catch (error) {
    orderConfirmInputVisible.value = false
  }
}
// 弹窗 表单编辑 打开
const batchOptionsEvent = async (e, params = {}) => {
  let data = {}
  switch (e) {
    case "recipientAddress": // 编辑 收件地址
      data = {
        ...confirm.recipientAddress,
        type: e,
        form: { ...params.recipient, id: params.id },
        originOption: originOption.value,
        id: router.currentRoute.value.name,
        key: router.currentRoute.value.name,
      }
      // 沃尔玛 需要 初始化买家姓名
      if (params.platform_id == 4) {
        data.form.buyer_name = `${params.recipient.recipient_name}`
      }
      originOption.value.countryOpt = SelectCountryRef.value.optionsList
      data.originOption = originOption.value
      break
  }

  orderCurrentConfirm.value = data
  orderConfirmInputVisible.value = true
}

const tipRef = ref()
const tip = ref({
  visible: false,
  content: "",
  ref: null,
})
const updateTip = (val) => {
  tip.value = val
}
const isHoverTip = ref(false)
const mouseenter = async ({ target }, item) => {
  if (!item.sku) return
  isHoverTip.value = true
  let table = await InventorySeeRef.value.getData(item)
  if (isHoverTip.value && updateTip) {
    updateTip({ visible: true, data: table, ref: target })
  }
}
const mouseleave = () => {
  isHoverTip.value = false
  updateTip &&
    updateTip({
      visible: false,
      content: "",
      data: {},
      ref: null,
    })
}

import RecipientAddress from "./components/RecipientAddress.vue"

import AssembleSkuSee from "./components/assembleSkuSee.vue"
// sku 库存信息查看
import InventorySee from "./components/InventorySee.vue"
const InventorySeeRef = ref()
const openInventorySee = (item, row) => {
  InventorySeeRef?.value.open({ ...item, warehouse_id: row.warehouse_id, country: row.site, warehouse_name: row.logistics?.ship_warehouse_name, wms_attribute_cn: row.logistics?.transport_name })
}

// 弹窗 表格数据展示
import DialogTableInfo from "@/components/DialogTableInfo/index.vue"
import { dialogTabelInfoConfig } from "@/views/user/list/config.jsx"
const dialogTableInfoVisible = ref(false)
const tableInfoConfirm = ref({})
const openTableInfo = async (e, item) => {
  let configData = {}
  switch (e) {
    case "inventory":
      // 库存信息
      configData = dialogTabelInfoConfig.inventory
      const res = await configData.loadApi({ data: [{ sku: item.sku }] })
      configData.tableOptions.data = res.data[0].inventory
      break
    case "declare":
      // 申报信息
      configData = dialogTabelInfoConfig.declare
      configData.params = { customer_order_no: item.order_sn }
      break
    case "shopSaleList":
      // 订单店铺销售数据列表
      configData = dialogTabelInfoConfig.shopSaleList
      let params = getSubmitForm(tableRef.value.getQueryForm())
      // 问题订单参数
      if (props.type == "problem_order") {
        params.push({ field: "order_status", queryType: "terms", value: [2] })
      }
      const rps = await configData.loadApi({ query: params })
      configData.tableOptions.data = rps?.data
      break

    case "repairNumber":
      // 二手维修编号
      configData = dialogTabelInfoConfig.repairNumber
      configData.tableOptions.data = [item]
      break
    default:
      break
  }
  tableInfoConfirm.value = configData
  dialogTableInfoVisible.value = true
}
// 订单店铺销售数据列表
const openShopSaleList = () => {
  openTableInfo("shopSaleList")
}
// 备注编辑
import EditRemarks from "./Batch/EditRemarks/index.vue"
const editRemarksRef = ref()

const props = defineProps({
  type: { type: String, default: "list" },
})

import ActionBars from "./AllOrder/ActionBars"
let orderTotal = reactive({
  total: "",
  order_amount: "",
  order_amount_us: "",
})
// 采购历史记录
import PurchaseDtl from "./Batch/purchaseDtl/index.vue"
const PurchaseDtlRef = ref()
const purchaseDtlOpen = (row, item) => {
  PurchaseDtlRef.value.open(item)
}

const queryListParams = ref({})
const tableRef = ref()
// 表格 全部展开 收起
const expandStatus = ref(false)
const handleExpand = (e) => {
  let data = tableRef?.value?.$table.getData()

  switch (activeName.value) {
    case 0:
      data.forEach((item, i) => {
        item.expandStatus = e
        item.expandLogistics = e
      })
      break
    default:
      data.forEach((item) => {
        item.child.forEach((items) => {
          items.expandStatus = e
        })
      })
      break
  }

  // data.forEach((item, i) => {
  //   item.expandStatus = e
  //   item.expandLogistics = e
  // })
  // console.log(tableRef?.value?.$table)

  rendererView()
}

const type = ref("list")
// const params = ref({})
// 刷新列表
const getList = async () => {
  let rowsId = tableRef?.value.$table.getCheckboxRecords()?.map((v) => v.id)
  await tableRef?.value.query()
  let rows = tableRef?.value.$table.getData().filter((v) => rowsId.includes(v.id))
  tableRef?.value.$table.setCheckboxRow(rows, true)
  nextTick(() => {
    checkboxChange()
  })
}

const setParamGet = (params) => {
  tableRef?.value.setForm(params)
  setTimeout(() => {
    getList()
  }, 500)
}

const multipleSelection = ref([])
// 表格选择
const checkboxChange = (e) => {
  multipleSelection.value = tableRef?.value.$table.getCheckboxRecords().filter((v) => v.order_sn)
}
const showOrderProfit = ref(false)
import { ElMessage, ElMessageBox } from "element-plus"

import XForm from "@/components/XForm/index.vue"
import ExpandList from "@/components/ExpandList/index.vue"

// 日志
import Log from "@/components/Log/index.vue"
const logVisible = ref(false)
const logId = ref("")

import { fieldList, highFieldList, getSubmitForm, orderStatusShow } from "./config.jsx"
// 查询条件
import SelectWarehouse from "@/components/Selects/SelectWarehouse/index.vue"
import SelectShippingMethod from "@/components/Selects/SelectShippingMethod/index.vue"
import SelectCountry from "@/components/Selects/SelectCountry/index.vue"
const SelectCountryRef = ref()

import SelectsShopCascade from "@/components/Selects/SelectsShopCascade/index.vue"
// 高级搜索
import SelectProductCategories from "@/components/Selects/ProductCategories"
// 订单排程策略 枚举
const strategyOpt = ref([
  { label: "已执行", value: 1 },
  { label: "未执行", value: 0 },
])
const strategyExecuteOpt = ref([])
const preferredOpt = ref([])
import schedulingApi from "@/views/order-strategy/scheduling-strategy/api"
import logisticsApi from "@/views/order-strategy/logistics-preferred/api"

//  订单类型 tab
const activeName = ref(0)
const activeNameLod = ref(0)
const tableRefShow = ref(true)
const isTabelColumn = ref([]) // 当前如渲染表格 列
const isApi = ref(null) // 当前 表格api
const formStore = ref({ 0: {}, 1: {}, 2: {} })

const handleClick = (val, isQuery = true) => {
  let data = tableRef?.value.getForm()
  formStore.value[activeNameLod.value] = data

  // tableRefShow.value = false
  // tableOptins.scrollY.enabled = activeName.value == 0
  nextTick(() => {
    // tableRefShow.value = true
    tableRef?.value?.$table.reloadData()
    nextTick(() => {
      switch (val) {
        case 0: // 全部订单
          isTabelColumn.value = [...tableOptins.columns, ...tableOptinos.columns]
          isApi.value = tableOptinos.api
          break
        case 1: // 可合并
          isTabelColumn.value = [...tableOptins.columns, ...OrderCanMergedTableOptinos.columns]
          isApi.value = OrderCanMergedTableOptinos.api
          break
        case 2: // 已合并
          isTabelColumn.value = [...tableOptins.columns, ...OrderMergedTableOptinos.columns]
          isApi.value = OrderMergedTableOptinos.api
          break
      }
      nextTick(() => {
        rendererView()
        if (!isQuery) return
        tableRef?.value?.resetForm()
        if (Object.keys(formStore.value[val]).length) {
          tableRef?.value.setForm(formStore.value[val])
          query()
        } else {
          formReset()
        }
        activeNameLod.value = val
      })
    })
  })
}

// 左边栏状态
const showLeftF = () => {
  pageComfig.value.isShowLeft = !pageComfig.value.isShowLeft
  rendererView()
}
const defaultProps = {
  children: "children",
  label: "label",
}
const treeData = [
  {
    label: "订单跟单",
    children: [
      { label: "2天前未发货订单", type: "1", date: "2" },
      { label: "5天前未发货订单", type: "1", date: "5" },
      { label: "7天前未发货订单", type: "1", date: "7" },
      { label: "15天前未发货订单", type: "1", date: "15" },
    ],
  },
  {
    label: "问题订单",
    children: [
      { label: "1天前未处理问题单", type: "2", date: "1" },
      { label: "2天前未处理问题单", type: "2", date: "2" },
      { label: "3天前未处理问题单", type: "2", date: "3" },
    ],
  },
  {
    label: "采购跟单",
    children: [
      { label: "2天前未采购订单", type: "3", date: "2" },
      { label: "5天前未采购订单", type: "3", date: "5" },
      { label: "7天前未采购订单", type: "3", date: "7" },
    ],
  },
  {
    label: "订单标发",
    children: [
      { label: "剩余1天未标发订单", type: "4", date: "24" },
      { label: "剩余2天未标发订单", type: "4", date: "48" },
    ],
  },
]
import { formatDate } from "@/utils"
const getTime = (num = 0) => {
  const temp = new Date()
  temp.setTime(temp.getTime() - 3600 * 1000 * 24 * num)
  const start = formatDate(new Date(temp.setHours(0, 0, 0, 0)))
  const end = formatDate(new Date(new Date().setHours(23, 59, 59, 0)))
  return [start, end]
}
// 左边栏 快捷搜索
const handleNodeClick = (data) => {
  if (!data.type) return
  let parmas = {}
  switch (data.type) {
    case "1":
      parmas = {
        shipping_type: 2,
        documentary_time: data.date,
      }
      break
    case "2":
      parmas = {
        order_time: getTime(data.date),
        order_status: [2],
      }
      break
    case "3":
      parmas = {
        order_time: getTime(data.date),
        order_status: [3],
        shipping_type: 2,
      }

      break
    case "4":
      parmas = {
        shipping_type: 2,
        mark_shipment_status: [1, 2, 4],
        delivery_time_limit: {
          script: "<",
          val: data.date,
        },
      }
      break
  }
  tableRef?.value.setForm(parmas)
  getList()
}

import { getCurrency, apiGetWarehouseEnum, goodsBaseGetEnums, getShippingService, getLogisticsAttributes } from "@/api/public"
const getOption = async () => {
  originOption.value.countryOpt = (await getCurrency()).data.map((v) => ({ label: v.label, value: v.label }))
  originOption.value.wmsAttribute = (await apiGetWarehouseEnum()).data.wms_attribute
  let shippingService = (await getShippingService()).data

  shippingService = Object.entries(shippingService).map((v) => ({ label: v[0], options: v[1].map((x) => ({ label: x.srv_name, value: x.id })) }))
  originOption.value.shippingService = shippingService

  // 产品状态
  originOption.value.productStatusTextOpt = (await goodsBaseGetEnums({ name: ["goods.GoodsSku"] })).data["goods.GoodsSku"][0].salesStatusText

  strategyExecuteOpt.value = (await schedulingApi.query({ pageNum: 1, pageSize: 9999 })).data.map((v) => ({ label: v.strategy_name, value: v.id }))
  preferredOpt.value = (await logisticsApi.query({ pageNum: 1, pageSize: 9999 })).data.map((v) => ({ label: v.rule_name, value: v.id }))
  // 产品物流属性
  originOption.value.logistics_attributes = (await getLogisticsAttributes({ pageSize: 9999 }))?.data
}
// 搜索条件 表单配置
const formOption = ref({ inline: true })
// 枚举 数据
const originOption = ref({
  booleanOption: [
    { label: "是", value: 1 },
    { label: "否", value: 0 },
  ],
})

// 查询
const query = () => {
  tableRef?.value.$table.commitProxy("query")
}

// 渲染表格列
const rendererView = (e) => {
  nextTick(() => {
    tableRef?.value?.$table.loadColumn(isTabelColumn.value)
  })
}
import action from "@/utils/action.js"
const RecipientAddressRef = ref()
const handleFunction = ref({
  // 查看详情
  handleDetail: (id) => {
    router.push(`/user/list/detail?id=${id}`)
  },
  // 编辑
  handleEdit: (id) => {
    router.push(`/user/list/addUpdata?id=${id}&type=edit`)
  },
  // 复制
  handleCopy: (row) => {
    let url = `/user/list/add?id=${row.id}&type=copy`
    router.push(url)
  },
  // 日志
  handleLog: (item) => {
    logId.value = item.id
    logVisible.value = true
  },
  // 打开 申报信息 弹窗
  openDeclare: (row) => {
    openTableInfo("declare", row)
  },

  // 打开收件地址 弹窗
  openRecipientDtl: (row) => {
    batchOptionsEvent("recipientAddress", row)
  },

  // 备注
  editRemark: (row, item) => {
    if (!item.edit) return
    editRemarksRef.value.visible = true
    editRemarksRef.value.batchType = false
    editRemarksRef.value.remarkText = row[item.field]
    editRemarksRef.value.remarkType = item.field
    editRemarksRef.value.remarkId = [row.id]
  },

  // isShowOrderProfit: () => {
  //   return showOrderProfit.value
  // },
  rendererView: () => {
    nextTick(() => {
      tableRef?.value?.$table.loadColumn(isTabelColumn.value)
    })
  },
  // 跳转到ebay客服系统写邮件
  gotoWrite: (row) => {
    action.setGlobalState({
      changeMicoTabsPath: {
        path: "/crm/emailFolder/write",
        type: "push",
        query: {
          typeField: "system_order_id",
          ebay_order_id: row.order_sn,
        },
      },
    })
  },
  // 跳转合并订单 tab
  gotoConsolidateOrder: (row) => {
    activeName.value = 2
    // 切换tag 不主动请求数据
    handleClick(2, false)
    setTimeout(() => {
      let data = tableRef?.value.getForm()
      data.orderSnRange = { type: "order_sn", value: row.order_sn }
      tableRef?.value.setForm(data)
      query()
      activeNameLod.value = 2
    }, 500)
  },
})
const formReset = (form) => {
  if (props.type != "problem_order") {
    nextTick(() => {
      let data = tableRef?.value.getForm()
      data.timeRange.value = getTime(90)
      tableRef?.value.setForm(data)
      query()
    })
  }
}

import {
  tableOptinos,
  pageComfig, // 页面 配置项
  handleFunctions, // 操作
  OrderCanMergedTableOptinos, //可合并
  OrderMergedTableOptinos, //已合并
  getFlag,
} from "./configOrderList.jsx"

const show = ref(false)
//获取下拉数据
onMounted(async () => {
  isTabelColumn.value = [...tableOptins.columns, ...tableOptinos.columns]
  isApi.value = tableOptinos.api
  rendererView()

  // 页面 配置项
  pageComfig.value = {
    type: props.type,
  }
  nextTick(() => {
    handleFunctions.value = handleFunction.value
    setTimeout(() => {
      show.value = true
      tableRef?.value?.updateScroll()
    }, 100)
  })

  getOption()
})
onActivated(() => {
  tableRef?.value?.updateScroll()
  nextTick(() => {}).then(() => {
    console.log("从新进入")
    // 订单状态  筛选 显示隐藏
    orderStatusShow.value = props.type != "problem_order"

    const { form, type, date, key } = history.state || {}
    // 看板页 跳转  赋值查询参数
    if (form == "home") {
      if (type == "order_status") {
        tableRef?.value.setForm({
          order_status: [Number(key)],
        })
      }
      if (type == "shipping_status") {
        tableRef?.value.setForm({
          pay_status: 1,
          documentary_time: date,
        })
      }
      getList()
    } else {
      rendererView()
    }
  })
})
// 列表行 样式
const rowStyle = ({ row, rowIndex }) => {
  let styles = {}
  if (row?.order_status_desc == "取消订单") {
    styles.background = "var(--base-danger-bg)"
  }
  return styles
}

// 单元格样式
const getCellStyle = ({ row, column }) => {
  // console.log(activeName.value)
  // if (!tableRef?.value?.$table.$el.querySelector(".fixed-left--wrapper")) return
  // if (!document.getElementsByClassName("vxe-table--body-wrapper fixed-left--wrapper").length) return
  switch (activeName.value) {
    case 0:
      return tableOptinos.cellStyle({ row, column })
      break
    // case 1:
    //   return OrderCanMergedTableOptinos.cellStyle({ row, column })
    //   break
    // case 2:
    //   return OrderMergedTableOptinos.cellStyle({ row, column })
    //   break
    //   break
  }
  return {}
}

// 列表配置
const tableOptins = reactive({
  formConfig: {
    save: "/oms/user/list", // 必填，唯一
    data: {
      platform_id: "",
      pay_status: 1,
      shipping_type: "",
      order_sn: "",
      skuRange: { type: "products.sku", value: "" },
      orderSnRange: { type: "order_sn", value: "" },
      trackRange: { type: "real_track_no", value: "" },
      timeRange: { type: "create_time", value: props.type == "problem_order" ? null : getTime(90) },
      timeRangeProducts: { type: "products.product_added_time", value: [] },
    },
  },
  // rowId: "order_sn",
  rowStyle: rowStyle,
  cellStyle: getCellStyle,
  rowConfig: {
    isHover: true,
    keyField: "order_sn",
  },
  // showOverflow: true,
  // showOverflow:false,
  pagerConfig: {
    pageNum: 1,
    pageSize: 10,
    pageSizes: [10, 15, 20, 50, 100],
  },
  // scrollY: { enabled: true },
  scrollY: { enabled: false },
  // scrollY: { oSize: -2 },
  columns: [{ type: "checkbox", fixed: "left", align: "center", width: 40 }],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        console.log("----------proxyConfig--query----------")
        multipleSelection.value = []
        return queryList({ query: getSubmitForm(form), ...page })
      },
    },
  },
})

const queryList = (param = {}) => {
  return new Promise(async (resolve, reject) => {
    let params = { ...param }

    queryListParams.value = params.query
    if (props.type == "problem_order") {
      // 问题订单参数
      params.query.push({
        field: "order_status",
        queryType: "terms",
        value: [2],
      })
    }
    // 可合并订单
    if (activeName.value == 1) {
      params.query = [...params.query, { field: "recipient_country", value: "", queryType: "term", contact: 2 }, { field: "recipient_preferred_address", value: "", queryType: "term", contact: 2 }]
    }
    let res = await isApi.value(params)
    switch (activeName.value) {
      case 0:
        orderTotal = {
          total: res?.total,
          order_amount_us: res?.data?.order_amount_us,
          order_amount: res?.data?.order_amount,
        }
        let selectCountry = SelectCountryRef?.value?.optionsList || []
        selectCountry = Object.fromEntries(selectCountry?.map((v) => [v.country, v.name]))
        res.data = res?.data?.orders || []
        res?.data?.forEach((item) => {
          item.expandStatus = false
          item.expandLogistics = false
          !item.recipient && (item.recipient = {})
          item.recipient.country_cn = selectCountry[item.recipient?.recipient_country]
        })
        res.data = await tableOptinos.setWarehouseParams(res.data)
        // res.data.unshift({})
        break
      case 1:
        res?.data?.forEach((item, i) => {
          item.child.forEach((items) => {
            items.expandStatus = false
            items.canMerged = 1
          })
        })
        // console.log(res.data)
        res.data = await OrderCanMergedTableOptinos.setWarehouseParams(res.data)
        break
      case 2:
        // res.data = res?.data?.orders || []
        res?.data?.forEach((item, i) => {
          item.child.forEach((items) => {
            items.expandStatus = false
          })
        })
        res.data = await OrderMergedTableOptinos.setWarehouseParams(res.data)
        break
    }
    tableRef?.value?.$table.reloadData([])
    resolve(res)
  })
}
// 列表 商品信息  展开收起
const getRows = (rows, expand) => {
  const { items = [] } = rows || {}
  if (rows.expandStatus) return items
  if (!items?.length) return []
  if (items.length > 0 && items.length < 1) {
    return items
  }
  if (!rows.expandStatus) {
    return items?.slice(0, 1)
  }
}
// 跳转asin 链接
const openAsinLink = (item) => {
  window.open(item.asin_link)
}
// 无法关联SKU
import UnableAssociateSku from "./AllOrder/UnableAssociateSku/index.vue"
const unableSkuVisible = ref(false)
const UnableAssociateSkuRef = ref()
// const selectRow = ref({})
// 异常订单 操作
const handleProblem = (item) => {
  // console.log(item.problem_cause_id)
  if (!item.problem_cause_id?.map(Number).includes(1)) return
  // 关联sku
  console.log("关联sku")

  if (!item.items?.length) return
  unableSkuVisible.value = true
  // open

  UnableAssociateSkuRef.value.open(JSON.parse(JSON.stringify(item)))
  // selectRow.value = JSON.parse(JSON.stringify(item))
}

import ProductApi from "@/components/SelectProduct/api"
const onSku = (row, item) => {
  if (item.sku) {
    ProductApi.query({ sku: [item.sku] }).then((res) => {
      action.setGlobalState({
        changeMicoTabsPath: {
          path: "/goods/task/product/detail",
          type: "push",
          query: {
            type: "view",
            spuId: res.data?.[0].spu_id,
            sku: item.sku,
          },
        },
      })
    })
  } else {
    handleProblem(row)
  }
}

import { apiGetWarehouseInventoryList } from "@/api/public"
// 查看组合sku
const assembleSkuSee = ref()
const openAssembles = async (item, row = {}) => {
  const warehouseParams = item.assembles.map((items) => ({
    item_sku: items.sku,
    rowId: row.id,
    warehouse_id: row.warehouse_id || "",
  }))

  let assembles = item.assembles
  let warehouseData = (await apiGetWarehouseInventoryList({ data: warehouseParams })).data
  warehouseData.forEach((v) => {
    assembles.forEach((val) => {
      if (v.item_sku == val.sku) {
        val.inventory = v.inventory
      }
    })
  })
  assembleSkuSee.value.formData = {
    sku: item.sku,
    custom_sku: item.custom_sku,
    i_robot_box_sku: item.i_robot_box_sku,
    tableData: assembles,
  }
  assembleSkuSee.value.open()
}
</script>
<style lang="scss" scoped>
@import "./style.scss";
:deep(.row-item) {
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 4px;
  margin-bottom: 2px;
}
.table-view {
  :deep(.fixed-right--wrapper) {
    margin-top: -1px !important;
  }
  :deep(.fixed-left--wrapper) {
    margin-top: -1px !important;
    border-top: none;
  }
}
:deep(.t-info) {
  color: #ff0000 !important;
  .v-text-content {
    color: #ff0000 !important;
  }
}
</style>
